import axios from 'axios'
import { getToken, removeToken } from '@/util/auth'
import { Message } from 'element-ui'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'

const service = axios.create({
    baseURL: 'http://localhost:3006',
    timeout: 5000,
    withCredentials: true,
})

//类节流阀
let flag = true
let clearTime = (time = 1500, callback) => {
    setTimeout(() => {
        flag = true;
        callback && callback()
    }, time);
}
//拦截器
service.interceptors.request.use((config) => {
    nprogress.start()
    const Authorization = getToken()
    if (Authorization) {
        config.headers['Authorization'] = Authorization
    }
    return config;
})
service.interceptors.response.use((res) => {
    // service(res.config) 再次请求
    // console.log(res);
    if (res.data.status === 401) {
        if (flag) {
            flag = false
            Message({
                message: '登录过期了!',
                type: 'error',
                duration: 3000
            })
            //1.5s后才可以再次触发
            clearTime()
        }
        removeToken();
        // setTimeout(() => {
        //     window.location.href = '/'
        // }, 1000);
    }
    nprogress.done()
    return res
})

export default service